package com.cxx.home.schedule;

import com.cxx.home.dto.message.MailMessageDto;
import com.cxx.home.entity.Task;
import com.cxx.framework.web.CustomException;
import com.cxx.home.mapper.TaskMapper;
import com.cxx.home.service.MessageService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;

@Slf4j
public class QuartzJob implements Job {
    @Resource
    private TaskMapper taskMapper;

    @Resource
    private MessageService messageService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        Long taskId = jobDataMap.getLong("id");

        Task task = taskMapper.selectById(taskId);
        try {
            JsonNode taskContent = objectMapper.readTree(task.getContent());

            switch (task.getType()) {
                case TaskType.EMAIL:
                    handleEmailTask(taskContent);
                    break;
                case TaskType.SMS:
                    break;
            }
        } catch (Exception e) {
            throw new CustomException("执行任务错误:", e.getMessage());
        }
    }

    private void handleEmailTask(JsonNode taskContent) {
        MailMessageDto mailMessageDto = new MailMessageDto();
        mailMessageDto.setTo(taskContent.get("to").asText());
        mailMessageDto.setSubject(taskContent.get("subject").asText());
        mailMessageDto.setBody(taskContent.get("body").asText());

        messageService.sendMailMessage(mailMessageDto);
    }
}
